<template>
  <div>
    <h1>form表单</h1>
    <el-form label-width="100px" :model="form" :rules="rules" ref="form">
      <el-form-item label="手机号" v-model="form.tel" prop="tel">
        <el-input></el-input>
      </el-form-item>
      <el-form-item label="用户名" v-model="form.username" prop="username">
        <el-input></el-input>
      </el-form-item>
      <el-form-item label="密码" v-model="form.password" prop="password">
        <el-input show-password></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="btnclick" type="primary">提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
//  el-form:表单组件标签
//    label-width:表单每一项标题的宽度
//    el-form-item:表单内的每一项
//    label:该项的标题
//    表单每一项内再包含表单元素
//    表单验证
//    1.el-form上绑定model(表单的数据)
//    2.el-form上绑定rules(验证规则)
//    3.再el-form-item上绑定prop(需要验证项的字段名)
//    rules:{
//        el-form-item上绑定的props值:[
//            {required:true,message:'错误信息',trigger:'change/blur'},
//            {min:最小长度,max:最大长度,message:'错误信息',trigger:'change/blur'}
//        ]
//    }
/* 自定义表单验证
   rules:{
     prop的值:[
       {required:true,message:'错误信息',trigger:'change'},
       {validator:(rule,value,callback)=>{
         rule:当前的规则
         value:当前 验证的值
         callback:它是一个回调函数
           验证成功:callback()
           验证失败:callback(new Error('错误的信息))
       },trigger:'change'},
     ]
   } */
export default {
  data () {
    return {
      form: {
        username: '',
        password: '',
        tel:''
      },
      rules: {
        tel: [
          { required: true, message: '请输入手机号', trigger: 'change' },
          {validator:(rule,value,callback)=>{
            const reg=/^(?:(?:\+|00)86)?1[3-9]\d{9}$/
           reg.test(value)?callback():callback(new Error('请输入正确的手机号'))
          },trigger: 'change'}
        ],
        username: [
          { required: true, message: '请输入用户名', trigger: 'change' },
          { min: 3, max: 5, message: '长度再3到5个字符', trigger: 'change' },
          {validator:(rule,value,callback)=>{
            value.startwith('ab')?callback();callback(new Error('必须以ab开头'))
          }}
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'change' },
          { min: 6, max: 12, message: '长度再6到12个字符', trigger: 'change' }
        ]
      }
    }
  },
  methods: {
    btnclcik(){
      this.$refs.form.validate()
    }
  },
}
</script>

<style></style>
